
import json
import random
import time

from flask import Blueprint, make_response, request, jsonify

from tools.myjwt import mjwt
from tools.captcha.captcha import captcha
from application.models.users.user import *
from  tools.myredis import r
from tools.comm import sendMsg

user_blue = Blueprint("userblue",__name__)

@user_blue.route("/reg")
def reg():
    res = User.query.all()
    print(res)
    return '欢迎使用flask'

@user_blue.route("/getcode")
def getcode():

    name,text,image = captcha.generate_captcha()
    uuid = str(request.args.get('uuid'))
    r.str_add(uuid,str(text),60)
    res = make_response(image)
    res.headers['Content-Type'] = "image/jpg"
    return res

@user_blue.route("/sendSmsCode",methods=['POST'])
def sendSmsCode():
    data = request.data
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        mobile = data ['mobile']

        value = r.str_get(uuid)
        if value:
            if piccode.lower() == value.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({"code":10012,'msg':'一分钟不能重复发'})

                scode = random.randint(10000,99999)

                flag = sendMsg(mobile,scode)
                if flag == True:
                    r.str_add(mobile,scode,60)
                    r.del_str(uuid)
                    return jsonify({'code': 200, 'msg': '图片验证码成功'})
                else:
                    return jsonify({'code':10013,'msg':'发送验证码失败'})

            else:
                return jsonify({'code': 10011, 'msg': '图片验证码错误'})
        else:
            return jsonify({'code':10010,'msg':'图片验证码不存在'})



@user_blue.route("/login",methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        mcode = data['code']
        mobile = data['mobile']
        code = r.str_get(mobile)
        if code:
            if int(code) == int(mcode):
                user = User.query.filter(User.mobile==mobile).first()
                if user:
                    r.del_str(mobile)
                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile==mobile).first()
                token = str(mjwt.jwt_encode(data={'data':{'uid':user.id,'exp':int(time.time())}}))
                return jsonify({'code': 200, 'token': token, 'userid': user.id,'msg':'登录成功'})
            else:
                return jsonify({"code":10021,"msg":'验证码错误'})
        else:
            return jsonify({'code':10020,'msg':'验证码过期'})





